<template>
    <el-form :model="formData" :rules="formRules" size="small" :inline="false" label-width="100px" ref="formRef">
        <el-form-item label="事项主题" prop="title">
            <el-input v-model="formData.title" placeholder="请填写事项主题" clearable maxlength="32"/>
        </el-form-item>
        <el-form-item label="事项描述" prop="content">
            <el-input v-model="formData.content" placeholder="请填写事项描述" type="textarea" :rows="3"/>
        </el-form-item>
        <el-form-item label="关联" prop="">
            <el-select v-model="formData.customerId" :disabled="customerDisable" placeholder="请选择客户" clearable filterable @change="getOrders">
                <el-option v-for="customer in customerList" :key="customer.id" :label="customer.nickname" :value="customer.id"/>
            </el-select>
            <el-select v-model="selectedOrders" :placeholder="formData.customerId ? '请选择订单' : '请先选择客户'" :disabled="formData.customerId == null || formData.customerId == ''" value-key="id" clearable filterable multiple style="margin: 0 10px" collapse-tags collapse-tags-tooltip>
                <el-option v-for="order in orderList" :key="order.id" :label="order.orderSn" :value="order"/>
            </el-select>
            <el-select v-model="selectedProjects" placeholder="请选择项目" value-key="id" clearable filterable multiple collapse-tags collapse-tags-tooltip>
                <el-option v-for="project in projectList" :key="project.id" :label="project.nickname" :value="project"/>
            </el-select>
            <el-select v-model="selectedMarkets" placeholder="请选择市场" value-key="id" clearable filterable multiple collapse-tags collapse-tags-tooltip style="margin-left: 10px">
                <el-option v-for="market in marketList" :key="market.id" :label="market.shortName" :value="market"/>
            </el-select>
        </el-form-item>
        <el-form-item label="预估回款日期">
            <el-date-picker v-model="formData.occurDate" type="date" placeholder="请选择日期" size="small" value-format="YYYY-MM-DD" @change="dateChange"/>
        </el-form-item>

        <el-table class="table-list" :data="selectedOrders" size="small">
            <el-table-column label="订单号" prop="orderSn"/>
            <el-table-column label="客户名称" prop="customerName"/>
            <el-table-column label="订单类型">
                <template v-slot="{row}">
                    <span v-if="row.rootIn == 6">调整单</span>
                    <template v-else>
                        <span v-for="item in dictMap['orderSourceType']" :key="item.value" v-show="item.value == row.sourceType">{{ item.name }}</span>
                    </template>
                </template>
            </el-table-column>
            <el-table-column label="订单类别">
                <template v-slot="{row}">{{ row.classOther == 0 ? '个人' : '企业' }}</template>
            </el-table-column>
            <el-table-column class-name="order-goods" width="400">
                <template #header>
                    <el-row class="order-row-item order-border-none">
                        <el-col :span="6">产品名称</el-col>
                        <el-col :span="6">详情/规格</el-col>
                        <el-col :span="4">数量</el-col>
                        <el-col :span="4">单价(元)</el-col>
                        <el-col :span="4">折扣</el-col>
                    </el-row>
                </template>
                <template v-slot="{row}">
                    <div style="flex:1;display:flex;flex-direction: column;">
                        <div v-for="(order, index) in row.orderItemList" :key="order.id" style="flex: 1;height:100%">
                            <el-row class="order-row-item" style="height:100%">
                                <el-col :span="6">{{ order.spuName }}</el-col>
                                <el-col :span="6">{{ order.skuName }}</el-col>
                                <el-col :span="4">{{ order.skuQuantity }}</el-col>
                                <el-col :span="4">{{ order.skuPrice }}</el-col>
                                <el-col :span="4">{{ (order.promotionAmount + order.couponAmount + order['integrationAmount'] + order.realAmount).toFixed(2) }}</el-col>
                            </el-row>
                            <el-divider style="margin: 0 -8px;width:calc(100% + 16px);border-color:var(--el-border-color-light)" v-if="index < row.orderItemList.length - 1"/>
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="总价(元)" prop="totalAmount"/>
            <el-table-column label="折后价" prop="discountAmount"/>
            <el-table-column label="订单总金额" prop="totalAmount"/>
            <el-table-column label="分销金">
                <template v-slot="{row}">{{ getShareSaleMoney(row) }}</template>
            </el-table-column>
            <el-table-column label="应收金额" prop="payAmount"/>
            <el-table-column label="已收金额" prop="receiveMoney"/>
            <el-table-column label="支付状态">
                <template v-slot="{row}">{{ row['paymentTime'] ? '待付款' : '已付款' }}</template>
            </el-table-column>
            <el-table-column label="本次回款(元)">
                <template v-slot="{row}">
                    <el-input-number v-model="row['receiveAmount']" :controls="false" :max="(row.payAmount - row['receiveMoney']).toFixed(2)" :precision="2" size="small"/>
                </template>
            </el-table-column>
        </el-table>

        <el-row style="margin-bottom: 18px">
            <el-col :span="4">
                <el-form-item label="未回款(元)">{{ selectedCustomer ? selectedCustomer['receivableAmount'] : '-' }}</el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="本次回款(元)">
                    <el-input-number v-model="formData.amount" :controls="false" :precision="2" :max="selectedCustomer ? selectedCustomer['receivableAmount'] : 0"/>
                </el-form-item>
            </el-col>
            <el-col :span="4">
                <el-checkbox v-model="formData.invoiceDispatch" :true-label="1" :false-label="0">开票申请</el-checkbox>
            </el-col>
        </el-row>
        <el-form-item label="附件">
            <Document :file-group="formData.type" v-model:resultList="attachList" :limit="9" code="MONEY"/>
        </el-form-item>
        <el-form-item label="备注">
            <el-input v-model="formData.remark" type="textarea" :rows="3" maxlength="500"/>
        </el-form-item>
        <el-form-item label="回款确认人" prop="executorIds">
            <el-select v-model="formData.executorIds" placeholder="请选择确认人" clearable filterable multiple collapse-tags collapse-tags-tooltip>
                <el-option v-for="item in confirmUsers" :key="item.userId" :label="item.userName" :value="item.userId"/>
            </el-select>
        </el-form-item>
        <el-form-item label="抄送人">
            <el-button type="primary" @click="openPicker" icon="ele-User">选择抄送人</el-button>
            <el-tag v-for="(user, i) in copyUsers" :key="user.id" style="margin-left: 10px" closable @close="removeUser(i)">{{ user.name }}</el-tag>
        </el-form-item>
        <el-row justify="end" v-if="!formData.id"> <!-- 日历/事项列表编辑处理 -->
            <el-button size="small" @click="closeForm">取消</el-button>
            <el-button size="default" type="primary" v-if="!formData.id && !formData.agendaMatterId" @click="submitData(formRef)">保存</el-button>
            <el-button size="default" type="primary" v-else-if="formData.state == 0 || formData.state == 1" @click="matterConfirm">确认</el-button>
        </el-row>

        <org-picker ref="orgPicker" title="请选择抄送人" multiple type="user" :selected="copyUsers" @ok="confirmPick"/>
    </el-form>
</template>

<script>
// 应收回款

import {reactive, toRefs, ref, onMounted} from 'vue'
import Cookies from 'js-cookie'
import {formatDate} from '/@/utils/formatTime'
import relateItemApi from '/@/api/matter/relateItem'
import moneyApi from '/@/api/money/index'
import {ElMessage} from 'element-plus'
import Document from '/@/components/document/index.vue'
import commonApi from '/@/api/commonApi'
import {getDictByCodes} from '/@/api/sys/dict'
import OrgPicker from '/@/views/setting/workflow/process/OrgPicker.vue'
import moneyMatterApi from '/@/api/matter/money'
import {getRelatableMap} from '/@/api/matter'

export default {
    name: 'CollectionReceivable',
    emits: ['update:code'],
    props: {
        code: {
            default: null,
            type: String
        },
        customerId: {   // 客户id
            default: null,
            type: String
        },
        relatableMap: {
            type: Object,
            default: null
        }
    },
    components: {
        Document,
        OrgPicker
    },
    setup(props, context) {
        const {customerId, relatableMap} = toRefs(props)
        const formRef = ref()
        const orgPicker = ref()
        const state = reactive({
            formData: {
                id: null,
                title: '应收回款',
                content: '',
                occurDate: null,
                actionStartTime: null,
                actionEndTime: null,
                executorIds: [],    // 执行人同时也是该事项确认人
                copyIds: [],
                relateItems: [],
                remark: null,
                attach: '',
                attachNames: '',
                priority: 0,
                remindState: 'NONE',
                remindType: [],
                amount: 0,
                invoiceDispatch: 0,   // 开票申请 1开票 0不开票
                customerId: null,   // 表单验证用
                capitalStreamNo: null,    // 钱相关事项特有流水号, 系统自动生成
                capitalTypeId: null,
                capitalAccountId: null,
                divideAmount: {},   // 回款订单分配的金额
                type: 'RECEIVE_COLLECTION',
                targetData: {
                    id: null,
                    type: 1,
                    name: null
                }
            },
            formRules: {
                title: {required: true, message: '请填写事项主题', trigger: 'blur'},
                executorIds: {required: true, message: '请选择确认人', trigger: 'change'},
                amount: {required: true, message: '请填写本次回款金额', trigger: 'blur'},
                customerId: {required: true, message: '请关联客户', trigger: 'change'}
            },
            relatableItem: null,    // 可关联项
            customerDisable: false,   // 是否禁用客户选项
            selectedCustomer: null,   // 选中的客户对象
            copyUsers: [],      // 选中的抄送人
            customerList: [],   // 客户列表
            orderList: [],    // 订单列表
            projectList: [],  // 项目列表
            marketList: [],   // 市场列表
            selectedOrders: [],     // 选中的订单列表
            selectedProjects: [],   // 选中的项目列表
            selectedMarkets: [],    // 选中的市场列表
            confirmUsers: [],   // 确认人列表
            dictMap: {},    // 字典
            attachList: []    // 附件列表
        })

        const getOrders = () => {
            if (!state.formData.customerId) {
                return ElMessage.warning('请先选择客户！')
            }
            relateItemApi.getOrderList(state.formData.customerId).then(res => state.orderList = res.data).catch(e => console.log(e))
        }
        // 初始化确认人数据列表
        const initConfirmUser = () => {
            // 获取确认人列表（钱模块）
            moneyApi.getCapitalUsers('capitalStream').then(res => {
                state.confirmUsers = res.data
                // 获取确认人的历史选择记录
                moneyApi.getConfirmRecord(state.formData.type).then(res => {
                    if (res.data) {
                        state.formData.executorIds = []
                        res.data.forEach(confirmId => {
                            for (let i = 0; i < state.confirmUsers.length; i++) {
                                let confirmUser = state.confirmUsers[i]
                                if (confirmUser.userId == confirmId) {
                                    state.formData.executorIds.push(confirmId)
                                    break
                                }
                            }
                        })
                    } else {  // 没有历史选择记录
                        // 如果当前用户为确认人之一, 默认加入
                        let selfId = Cookies.get('userId')
                        for (let i = 0; i < state.confirmUsers.length; i++) {
                            let confirmUser = state.confirmUsers[i]
                            if (confirmUser.userId == selfId) {
                                state.formData.executorIds = [state.selfId]
                                break
                            }
                        }
                    }
                }).catch(e => console.log(e))
            }).catch(e => console.log(e))
        }
        // 计算订单分销金
        const getShareSaleMoney = (order) => {
            let result = 0
            order.orderItemList.forEach(item => result += item.saleMoney)
            return result
        }
        const dateChange = (val) => {
            if (val) {
                state.formData.actionEndTime = state.formData.actionStartTime = val + state.formData.actionStartTime.substring(10)
            }
        }
        // 初始化表单字段
        const initFormData = () => {
            state.formData = {
                id: null,
                title: '应收回款',
                content: '',
                occurDate: null,
                actionStartTime: null,
                actionEndTime: null,
                executorIds: [],    // 执行人同时也是该事项确认人
                copyIds: [],
                relateItems: [],
                remark: null,
                attach: '',
                attachNames: '',
                priority: 0,
                remindState: 'NONE',
                remindType: [],
                amount: 0,
                invoiceDispatch: 0,   // 开票申请 1开票 0不开票
                customerId: null,   // 表单验证用
                capitalStreamNo: null,    // 钱相关事项特有流水号, 系统自动生成
                capitalTypeId: null,
                capitalAccountId: null,
                divideAmount: {},   // 回款订单分配的金额
                type: 'RECEIVE_COLLECTION',
                targetData: {
                    id: null,
                    type: 1,
                    name: null
                }
            }
        }
        const openPicker = () => {
            orgPicker.value.show()
        }
        // 抄送人确认选择回调
        const confirmPick = (users) => {
            if (users && users.length > 0) {
                state.copyUsers = users
                state.formData.copyIds = []
                users.forEach(user => state.formData.copyIds.push(user.id))
            } else {
                state.copyUsers = state.formData.copyIds = []
            }
        }
        // 抄送人标签移除方法
        const removeUser = (index) => {
            state.copyUsers.splice(index, 1)
            state.formData.copyIds.splice(index, 1)
        }
        const submitData = (formEl) => {
            formEl.validate(async (valid) => {
                if (!valid) {
                    return false
                }
                let params = JSON.parse(JSON.stringify(state.formData))
                // 列表转逗号分割字符串提交
                if (state.attachList.length > 0) {  // 组装附件地址和名称
                    for (let i = 0; i < state.attachList.length; i++) {
                        let item = state.attachList[i]
                        params.attach += item.src
                        params.attachNames += item.name
                        if (i < state.attachList.length - 1) {
                            params.attach += ','
                            params.attachNames += '，'
                        }
                    }
                }
                params.targetData.id = state.selectedCustomer.id
                params.targetData.name = state.selectedCustomer.nickname
                // 客户的关联项
                let relatable = state.relatableItem['Customer']
                params.relateItems = [{
                    code: relatable.code,
                    agendaMatterRelatableId: relatable.id,
                    seRelateDataId: state.selectedCustomer.id,
                    label: relatable.label + '/' + state.selectedCustomer.nickname
                }]
                // 订单
                if (state.selectedOrders.length > 0) {
                    let relatable = state.relatableItem['Order']
                    state.selectedOrders.forEach(order => {
                        // 组装采购单分配的付款金额
                        params.divideAmount[order['id']] = order['receiveAmount']
                        params.relateItems.push({
                            code: relatable.code,
                            agendaMatterRelatableId: relatable.id,
                            seRelateDataId: order['id'],
                            label: relatable.label + '/' + order['orderSn']
                        })
                    })
                }
                // 市场
                if (state.selectedMarkets.length > 0) {
                    let relatable = state.relatableItem['Market']
                    state.selectedMarkets.forEach(market => params.relateItems.push({
                        code: relatable.code,
                        agendaMatterRelatableId: relatable.id,
                        seRelateDataId: market['id'],
                        label: relatable.label + '/' + market['shortName']
                    }))
                }
                // 项目
                if (state.selectedProjects.length > 0) {
                    let relatable = state.relatableItem['Project']
                    state.selectedProjects.forEach(project => params.relateItems.push({
                        code: relatable.code,
                        agendaMatterRelatableId: relatable.id,
                        seRelateDataId: project['id'],
                        label: relatable.label + '/' + project['nickname']
                    }))
                }

                moneyMatterApi.submitMatter(params).then(res => {
                    if (res.data) {
                        // 提交事项后, 提交附件
                        commonApi.fileRelevanceModule(state.attachList)
                        ElMessage.success('提交成功！')
                        closeForm()
                    }
                }).catch(e => console.log(e))
            }).catch(e => console.log(e))
        }
        const matterConfirm = () => {
            moneyMatterApi.moneyConfirm(state.formData).then(res => {
                if (res.data) {
                    ElMessage.success('确认成功！')
                    closeForm()
                }
            }).catch(e => console.log(e))
        }
        const closeForm = () => {
            context.emit('update:code', '')
        }

        onMounted(() => {
            if (relatableMap.value == null) {
                getRelatableMap().then(res => state.relatableItem = res.data).catch(e => console.log(e))
            } else {
                state.relatableItem = JSON.parse(JSON.parse(relatableMap.value))
            }
            initFormData()
            // 如果带入了客户id, 那就不允许再修改（客详情发起）
            if (customerId.value) {
                state.formData.customerId = customerId.value
                state.customerDisable = true
                getOrders()
            }
            // 客户列表
            relateItemApi.getCustomerList().then(res => {
                state.customerList = res.data
                for (let i = 0; i < state.customerList.length; i++) {
                    let customer = state.customerList[i]
                    if (state.formData.customerId == customer.id) {
                        state.selectedCustomer = customer
                        break
                    }
                }
            }).catch(e => console.log(e))
            // 项目、市场列表
            relateItemApi.getProjectList().then(res => state.projectList = res.data).catch(e => console.log(e))
            relateItemApi.getMarketList().then(res => state.marketList = res.data).catch(e => console.log(e))
            initConfirmUser()
            // 行动时间默认现在
            let nowTime = formatDate(new Date(), 'YYYY-mm-dd HH:MM:SS')
            state.formData.actionStartTime = state.formData.actionEndTime = nowTime
            state.formData.occurDate = nowTime.substring(0, 10)
            // 加载字典
            getDictByCodes(['orderSourceType']).then(res => state.dictMap = res.data).catch(e => console.log(e))
        })

        return {
            formRef,
            orgPicker,
            ...toRefs(state),
            getOrders,
            getShareSaleMoney,
            submitData,
            closeForm,
            dateChange,
            openPicker,
            confirmPick,
            removeUser,
            matterConfirm
        }
    }
}
</script>

<style scoped lang="scss">
:deep(.el-table__header-wrapper .el-table__cell) {
    background: var(--el-color-primary-light-9);
    color: var(--next-bg-menuBar-light-1);
}

.table-list {
    border: 1px solid var(--el-table-border-color);
    border-bottom: none;
    margin-bottom: 18px;

    :deep(thead .cell) {
        display: flex;
        align-items: center;
        justify-content: center;
    }

    :deep(thead th:last-child .cell) {
        justify-content: center;
    }

    :deep(thead .el-icon) {
        margin-top: -2px;
        cursor: pointer;
    }

    .primary {
        cursor: pointer;
        color: var(--el-color-primary);
    }

    :deep(.el-button) {
        margin-left: 0;
        margin-right: 12px;
    }

    :deep(.el-table__body td.el-table__cell) {
        border-right: 1px solid var(--el-border-color-light);
        padding: 0;

        &:last-child {
            border-right: none;
        }
    }

    .order-row-item {
        width: 100%;

        :deep(.el-col) {
            border-right: 1px solid var(--el-border-color-light);
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;

            &:last-child {
                border-right: none;
            }

            &:first-child,
            &:nth-child(2) {
                text-align: left;
                justify-content: flex-start;
                padding-left: 8px;
            }
        }
    }

    .order-border-none {
        :deep(.el-col) {
            border: none;
        }
    }
}
</style>
<style lang="scss">
.order-goods .cell {
    padding: 0;
}

.el-table__body .order-goods .cell {
    min-height: 70px;
    display: flex;
    align-items: stretch;
    padding: 0;
}
</style>
